package ch.ethz.fcl.metrobuzz.render.techniques.tesselation;

import org.lwjgl.util.glu.GLU;
import org.lwjgl.util.glu.GLUtessellator;
import org.lwjgl.util.glu.GLUtessellatorCallbackAdapter;
import org.lwjgl.util.glu.tessellation.GLUtessellatorImpl;

public class TessRender {
	private static GLUtessellator tess;

	private static void init() {
		// Create a new tessellation object
		tess = GLUtessellatorImpl.gluNewTess();

		// Set callback functions
		GLUtessellatorCallbackAdapter callback = new TessCallBack();
		tess.gluTessCallback(GLU.GLU_TESS_VERTEX, callback);
		tess.gluTessCallback(GLU.GLU_TESS_BEGIN, callback);
		tess.gluTessCallback(GLU.GLU_TESS_END, callback);
		tess.gluTessCallback(GLU.GLU_TESS_COMBINE, callback);
	}

	private static void renderContour(double obj_data[][]) {
		for (int x = 0; x < obj_data.length; x++) // loop through the vertices
		{
			tess.gluTessVertex(obj_data[x], 0, obj_data[x]); // store the vertex
		}
	}
	
	public static void render(int widingRule, double[][] vertex){
		if(tess == null)
			init();
		
		tess.gluTessProperty(GLU.GLU_TESS_WINDING_RULE, widingRule);
		tess.gluTessBeginPolygon(null);
		tess.gluTessBeginContour();
		renderContour(vertex);
		tess.gluTessEndContour();
		tess.gluTessEndPolygon();

		tess.gluDeleteTess();
	}

	public static void render(int widingRule, double[][] vertex, float[] color) {
		int vertexSize = vertex.length;
		float r = color[0];
		float g = color[1];
		float b = color[2];
		float a = 0;
		if (color.length == 4)
			a = color[3];
		else
			a = 1.0f;

		double[][] data = new double[vertexSize][7];
		for (int i = 0; i < vertexSize; i++) {
			data[i][0] = vertex[i][0];
			data[i][1] = vertex[i][1];
			if (vertex[0].length == 3)
				data[i][2] = vertex[i][2];
			else
				data[i][2] = 0;
			data[i][3] = r;
			data[i][4] = g;
			data[i][5] = b;
			data[i][6] = a;
		}

		if(tess == null)
			init();
		
		tess.gluTessProperty(GLU.GLU_TESS_WINDING_RULE, widingRule);
		tess.gluTessBeginPolygon(null);
		tess.gluTessBeginContour();
		renderContour(data);
		tess.gluTessEndContour();
		tess.gluTessEndPolygon();

		tess.gluDeleteTess();
	}
}
